import React, {useEffect, useState, useCallback} from 'react';
import StudentList from "./components/StudentList";
import './App.css';
import StuContext from './store/StuContext';

const App = () => {

    const [stuData, setStuData] = useState([]);

    const [loading, setLoading] = useState(false);

    const [error, setError] = useState(null);

    const fetchData = useCallback(async () => {
        try{
            setLoading(true);
            setError(null);
            const res = await fetch('http://localhost:1337/api/students')
            if(res.ok) {
                const data = await res.json()
                setStuData(data.data)
            }else{
                throw new Error('数据加载失败')
            }
        }catch (e){
            setError(e.message)
        }finally {
            setLoading(false)
        }
    }, [])

    useEffect(() => {
        fetchData()
    }, [fetchData]);

    return (
        <StuContext.Provider value={{fetchData}}>
            <div className="app">            
                <button onClick={fetchData}>加载数据</button>
                {(!loading && !error) && <StudentList stus={stuData}/>}
                {loading && <p>数据正在加载中...</p>}
                {error && <p>{error}</p>}
            </div>
        </StuContext.Provider>
    );
};

export default App;
